package com.zgf.lineTable;




/**
 * @author zgf
 * @date 2019/8/26 19:40
 */
public class ArrayList implements List {

    private Object[] elementData;

    private int size=0;

    public ArrayList() {
        //初始化长度设置为5
        this(5);
    }
    //给数组分配空间
    public ArrayList(int length) {
        elementData=new Object[length];
    }
    @Override
    public int size() {
        //返回链表长度
        return size;
    }

    @Override
    public Object get(int i) {
        if (i<0 || i>size){
            throw new RuntimeException("查询的位数超过数组长度："+i);
        }
        return elementData[i];
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }


    @Override
    public void add(Object e) {
        this.add(size,e);

    }

    /**
     * 数组扩容
    */
    private void grow(){
        //数组每次扩容为原来的二倍
        Object newArr[]=new Object[size*2];
        //旧数组把值赋给新数组
        for (int i=0;i<size;i++){
            newArr[i]=elementData[i];
        }

        elementData=newArr;
    }

    @Override
    public void add(int i, Object e) {

        if (size==elementData.length){
            grow();
        }
        //从最后一个数开始  把数依次往后挪一个
        for (int j=size;j>i;j--){
            elementData[j]=elementData[j-1];
        }
        elementData[i] =e;
        size++;

    }

    @Override
    public Object replace(int i, Object e) {
        elementData[i]=e;
        return elementData[i];
    }


    @Override
    public Object remove(int i) {
        if (i<0 || i>size){
            throw new RuntimeException("删除的位数越界！"+i);
        }
        //把第i个之后的数 依次往前挪
        for (int j=i-1;j<size-1;j++){
            elementData[j]=elementData[j+1];
        }
        size--;
        return elementData[i-1];
    }

    @Override
    public String toString() {
        if (size==0){
            return "[]";
        }
       StringBuilder builder=new StringBuilder("[");
        for (int i=0;i<size;i++){
            if (i==size-1){
                builder.append(elementData[i]);
            }else{
                builder.append(elementData[i]+",");
            }
        }
        builder.append("}");
        return builder.toString();
    }
}
